package com.godfrey.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.godfrey.shiro.realm.AccountRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author godfrey
 * @since 2021-01-02
 */
@Configuration
public class ShiroConfig {

    /**
     * 第一步：创建Realm对象
     *
     * @param
     * @return com.godfrey.realm.AccountRealm
     */
    @Bean
    public AccountRealm accountRealm() {
        return new AccountRealm();
    }

    /**
     * 第二步：创建DefaultWebSecurityManager，Realm对象放入DefaultWebSecurityManager
     *
     * @param accountRealm
     * @return org.apache.shiro.web.mgt.DefaultWebSecurityManager
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("accountRealm") AccountRealm accountRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(accountRealm);
        return securityManager;
    }

    /**
     * 第三步：创建ShiroFilterFactoryBean，DefaultWebSecurityManager对象放入hiroFilterFactoryBean
     *
     * @param securityManager
     * @return org.apache.shiro.spring.web.ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);

        //权限设置
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/main","authc");
        filterMap.put("/manager","perms[manager]");
        filterMap.put("/administrator","roles[administrator]");
        factoryBean.setFilterChainDefinitionMap(filterMap);
        //设置登录页面
        factoryBean.setLoginUrl("/login");
        //设置未授权页面
        factoryBean.setUnauthorizedUrl("/unauth");
        return factoryBean;
    }

    /**
     * ShiroDialect(方言）：shiro整合thymeleaf
     *
     * @param
     * @return at.pollux.thymeleaf.shiro.dialect.ShiroDialect
     */
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
}
